import { useState } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "~/components/ui/dialog";
import { Input } from "~/components/ui/input";
import { Button } from '~/components/ui/button';
import { Label } from "~/components/ui/label"; 

interface RegisterDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onRegisterSuccess: () => void;
  onNavigateToLogin: () => void;
}

export function RegisterDialog({
  open,
  onOpenChange,
  onRegisterSuccess,
  onNavigateToLogin,
}: RegisterDialogProps): React.JSX.Element {
  const [formData, setFormData] = useState({ 
    username: '', 
    email: '', 
    password: '',
    confirmPassword: '' // 添加确认密码字段
  });
  
  const [errors, setErrors] = useState<Record<string, string>>({}); // 错误信息状态

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // 验证表单
    const validationErrors: Record<string, string> = {};
    
    // 密码一致性验证
    if (formData.password !== formData.confirmPassword) {
      validationErrors.confirmPassword = '两次输入的密码不一致';
    }
    
    // 密码强度验证 (至少6个字符)
    if (formData.password.length < 6) {
      validationErrors.password = '密码至少需要6个字符';
    }
    
    // 用户名验证
    if (!formData.username.trim()) {
      validationErrors.username = '用户名不能为空';
    }
    
    // 邮箱格式验证
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(formData.email)) {
      validationErrors.email = '请输入有效的邮箱地址';
    }
    
    // 如果有错误，显示错误并阻止提交
    if (Object.keys(validationErrors).length > 0) {
      setErrors(validationErrors);
      return;
    }
    
    try {
      const response = await fetch('/api/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username: formData.username,
          email: formData.email,
          password: formData.password
        }),
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.detail || '注册失败');
      }
      
      // 注册成功后重置表单
      setFormData({ username: '', email: '', password: '', confirmPassword: '' });
      setErrors({});
      onRegisterSuccess();
    } catch (error) {
      let errorMessage = '注册失败，请稍后再试';
      if (error instanceof Error) {
        errorMessage = error.message;
      }
      // 设置服务器返回的错误
      setErrors({
        form: errorMessage
      });
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { id, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [id]: value
    }));
    
    // 清空当前字段的错误信息
    if (errors[id]) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[id];
        return newErrors;
      });
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange} className="flex items-center justify-center bg-black/50">
      <DialogContent className="sm:max-w-[425px] mt-[-20px] sm:mt-0">
        <DialogHeader>
          <DialogTitle className="text-lg">用户注册</DialogTitle>
        </DialogHeader>
        
        {/* 全局错误信息显示 */}
        {errors.form && (
          <div className="text-red-500 text-sm mb-4 bg-red-50 px-3 py-2 rounded">
            {errors.form}
          </div>
        )}
        
        <form onSubmit={handleSubmit} className="space-y-4">
          {/* 用户名字段 */}
          <div className="grid gap-2">
            <Label htmlFor="username">用户名</Label>
            <Input
              id="username"
              value={formData.username}
              onChange={handleInputChange}
              placeholder="请输入用户名"
              required
              className={errors.username ? 'border-red-500' : ''}
            />
            {errors.username && (
              <p className="text-red-500 text-xs">{errors.username}</p>
            )}
          </div>
          
          {/* 邮箱字段 */}
          <div className="grid gap-2">
            <Label htmlFor="email">邮箱</Label>
            <Input
              id="email"
              type="email"
              value={formData.email}
              onChange={handleInputChange}
              placeholder="请输入邮箱"
              required
              className={errors.email ? 'border-red-500' : ''}
            />
            {errors.email && (
              <p className="text-red-500 text-xs">{errors.email}</p>
            )}
          </div>
          
          {/* 密码字段 */}
          <div className="grid gap-2">
            <Label htmlFor="password">密码</Label>
            <Input
              id="password"
              type="password"
              value={formData.password}
              onChange={handleInputChange}
              placeholder="请输入密码（至少6位）"
              required
              className={errors.password ? 'border-red-500' : ''}
            />
            {errors.password && (
              <p className="text-red-500 text-xs">{errors.password}</p>
            )}
          </div>
          
          {/* 确认密码字段 */}
          <div className="grid gap-2">
            <Label htmlFor="confirmPassword">确认密码</Label>
            <Input
              id="confirmPassword"
              type="password"
              value={formData.confirmPassword}
              onChange={handleInputChange}
              placeholder="请再次输入密码"
              required
              className={errors.confirmPassword ? 'border-red-500' : ''}
            />
            {errors.confirmPassword && (
              <p className="text-red-500 text-xs">{errors.confirmPassword}</p>
            )}
          </div>
          
          <div className="flex items-center justify-end space-x-2 pt-2">
            <span className="text-sm text-muted-foreground">已有账号？</span>
            <Button
              variant="link"
              type="button"
              className="h-auto p-0 text-primary/80 hover:text-primary"
              onClick={onNavigateToLogin}
            >
              立即登录
            </Button>
          </div>
          
          <Button type="submit" className="w-full">
            立即注册
          </Button>
        </form>
      </DialogContent>
    </Dialog>
  );
}